import React from 'react';
import styles from './index.less';
import { Modal, Select, Table, Button, Space } from 'antd';
import { tableLocale } from '@/tool/components/PageEmpty';
// components
import { PageLoading, TRAlert, TRDefault, TRMessage } from '@/components';
import TRNotification from '@/utils/notification';
// api
import { batchDataSourceSave, forecastDataSource } from '../../services';
import { HttpCode } from '@/utils/contacts';

const ModalDatasourceComponent = ({
  buttonPermissions = [],
  stationMap,
  form,
  onClose = () => {},
}) => {
  const title = '预测数据源管理';
  const canSave = buttonPermissions.some((x) => x.menuCode === 'dataSourceSave');
  const [loading, setLoading] = React.useState(true);
  const [saving, setSaving] = React.useState(false);
  const [dataSource, setDataSource] = React.useState([]);
  const [changed, setChanged] = React.useState(false);

  React.useEffect(() => {
    fetch();
  }, []);

  const initOptions = (map) => {
    let opts = {};
    for (const key in map) {
      let value = null,
        options = [];
      (map[key] || []).map((x) => {
        if (!!x?.default) value = x.dataSourceId;
        options.push({
          label: x.dataSourceName,
          value: x.dataSourceId,
        });
      });
      opts[key] = value;
      opts[`${key}_options`] = options;
    }
    return opts;
  };

  const fetch = async () => {
    setLoading(true);
    const { startDate, endDate, settlementUnitList } = form;
    const res = await forecastDataSource({
      startDate,
      endDate,
      settlementUnitList,
    });
    setLoading(false);
    const resList = res?.results || [];
    let _table = [];
    resList.map((x) => {
      const stationId = Object.keys(x || {})?.[0];
      if (!stationId) return;
      _table.push({
        id: x.id,
        stationId,
        stationName: stationMap[stationId],
        ...initOptions(x[stationId]),
      });
    });
    setDataSource(_table);
    setChanged(false);
  };

  const handelCancel = async () => {
    // 取消
    let obj = { index: 1 };
    if (dataSource.length > 0 && changed) {
      obj = await TRAlert.show('当前工作将不被保存，继续执行此操作？');
    }
    obj?.index === 1 && onClose();
  };

  const handelSave = async () => {
    // 保存
    if (!canSave) return TRMessage.info('请联系管理员获取相关权限');
    if (saving) return;
    setSaving(true);
    const postData = {
      startDate: form.startDate,
      endDate: form.endDate,
      results: dataSource.map((x) => ({
        id: x.id,
        longSourceId: x.longSourceId,
        mediumSourceId: x.mediumSourceId,
        shortSourceId: x.shortSourceId,
        stationId: x.stationId,
      })),
    };
    const res = await batchDataSourceSave(postData);
    setSaving(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      TRMessage.success('保存成功');
      setChanged(false);
    } else {
      TRMessage.error(res?.message || '保存失败');
    }
  };

  const renderSelect = (v, r, code) => {
    const opts = r[`${code}_options`];
    if (!opts?.length) return <div className={styles.ept}>暂无</div>;
    return (
      <Select
        value={v}
        options={opts}
        style={{ width: '100%' }}
        placeholder="请选择"
        bordered={false}
        showArrow={false}
        allowClear={true}
        onChange={(selected) => {
          r[code] = selected;
          setDataSource([...dataSource]);
          setChanged(true);
        }}
      />
    );
  };

  const columns = () => [
    { dataIndex: 'stationName', title: '结算单元', width: 200 },
    {
      dataIndex: 'shortSourceId',
      title: '短期预测数据',
      width: 150,
      render: (v, r) => renderSelect(v, r, 'shortSourceId'),
    },
    {
      dataIndex: 'mediumSourceId',
      title: '中期预测数据',
      width: 150,
      render: (v, r) => renderSelect(v, r, 'mediumSourceId'),
    },
    {
      dataIndex: 'longSourceId',
      title: '长期预测数据',
      width: 150,
      render: (v, r) => renderSelect(v, r, 'longSourceId'),
    },
  ];

  return (
    <Modal
      wrapClassName={styles.modal}
      width={800}
      centered
      maskClosable={true}
      visible={true}
      title={title}
      footer={
        <Space size={16}>
          <Button onClick={handelCancel}>取消</Button>
          {dataSource.length > 0 && (
            <Button type="primary" onClick={handelSave}>
              保存
            </Button>
          )}
        </Space>
      }
      onCancel={handelCancel}
    >
      {loading ? (
        <PageLoading />
      ) : !dataSource?.length ? (
        <TRDefault type="emptysm" />
      ) : (
        <Table
          className={styles.table}
          columns={columns()}
          locale={tableLocale}
          dataSource={dataSource}
          pagination={false}
          rowKey="stationId"
          size="small"
        />
      )}
    </Modal>
  );
};

class ModalDatasource {
  __key__ = '';
  show = (props) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ModalDatasourceComponent
            {...props}
            onClose={() => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve();
            }}
          />
        ),
        duration: null,
      });
    });
  };
  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new ModalDatasource();
